package com.example.springdemo.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * {@link TimeConsume}注解的处理
 *
 * @author pengzhikang
 * @date 2021/10/13 16:52
 * @since 1.0.0
 */
@Aspect
@Component
public class TimeConsumeAspect {

    @Around("@annotation(timeConsume)")
    public Object computeTimeConsume(ProceedingJoinPoint proceedingJoinPoint, TimeConsume timeConsume) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();

        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        // 获取方法
        Method method = methodSignature.getMethod();

        // 创建日志
        Class<?> targetClass = proceedingJoinPoint.getTarget().getClass();
        Logger logger = LoggerFactory.getLogger(targetClass);
        logger.info("{} {}方法耗时：{} ms.", timeConsume.describe(), method.getName(), (endTime - startTime));
        return result;
    }
}
